package com.wxp.serviceImpl;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;

import com.modules.utils.MenuMapping;
import com.modules.utils.ResourceMapping;
import com.wxp.entity.Resource;

public class StartupRunner implements CommandLineRunner{
	 private static final Logger logger = LoggerFactory.getLogger(StartupRunner.class);
	 
	 @Autowired
	 ApplicationContext applicationContext;
	 
	 @Autowired
	 private ResourceServiceImpl resourceService;
	 
	@Override
	public void run(String... arg0) throws Exception {
		logger.info("startup runner");
		AbstractHandlerMethodMapping<RequestMappingInfo> objHandlerMethodMapping = (AbstractHandlerMethodMapping<RequestMappingInfo>)applicationContext.getBean("requestMappingHandlerMapping");
	    Map<RequestMappingInfo, HandlerMethod> mapRet = objHandlerMethodMapping.getHandlerMethods();
	    for(Map.Entry<RequestMappingInfo, HandlerMethod> entry : mapRet.entrySet()) {
	    		MenuMapping menuMapp = entry.getValue().getBeanType().getAnnotation(MenuMapping.class);
	    		if(menuMapp != null) {
	    			 if(entry.getValue().getMethodAnnotation(ResourceMapping.class)!=null&&entry.getValue().getMethodAnnotation(RequiresPermissions.class)!=null) {
	    				  ResourceMapping resourceMapping = entry.getValue().getMethodAnnotation(ResourceMapping.class);
	    				  RequiresPermissions requiresPermiss = entry.getValue().getMethodAnnotation(RequiresPermissions.class);
	    				  //System.out.println("有对应注解"+"请求URL："+entry.getKey().getPatternsCondition().getPatterns().toArray()[0] +"   请求资源名称："+resourceMapping.name()+"   请求资源类型"+resourceMapping.operation()+"    菜单名称："+menuMapp.name()+"  "+"   权限："+convertString(requiresPermiss.value()));
	    				  resourceService.save(new Resource(resourceMapping.operator(),menuMapp.name(),convertString(requiresPermiss.value()),entry.getKey().getPatternsCondition().getPatterns().toArray()[0].toString(),resourceMapping.name(),resourceMapping.operation().toString(),resourceMapping.parentOperator()));
	   	    	  	}
	    			
	    		}
	    }
	    logger.info("end runner");
		
	}
	private String convertString( String [] value) {
		String name = "";
		for(String val:value) {
			name = name+val+",";
		}
		if(StringUtils.isNotBlank(name)) {
			name= name.substring(0, name.lastIndexOf(","));
		}
		return name;
	}
}
